package org.example.GradeManagement;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.example.MyBatisUtils;
import org.example.mapper.StuGradeMapper;
import org.example.pojo.Grade;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class GradeForm extends JFrame{
    private JLabel titleLabel;
    private JButton addButton;
    private JButton deleteButton;
    private JButton updateButton;
    private JButton searchButton;
    private JButton exitButton;
    private JButton refreshButton;
    private DefaultTableModel tableModel;
    private JTable GradeTable;
    private JScrollPane scrollPane;


    public void mainFrom() {
        // 设置窗口标题
        setTitle("学生管理系统");

        // 创建面板
        JPanel panel = new JPanel(new BorderLayout());

        // 设置标题标签
        JPanel jPanel = new JPanel(new FlowLayout());
        titleLabel = new JLabel("学生成绩管理系统");
        titleLabel.setFont(new Font("SansSerif", Font.BOLD, 24));
        titleLabel.setHorizontalAlignment(JLabel.CENTER);
        JLabel jLabel = new JLabel("教师端");
        jPanel.add(titleLabel);
        jPanel.add(jLabel);

        // 设置按钮
        addButton = new JButton("增加");
        addButton.setPreferredSize(new Dimension(100, 30));
        deleteButton = new JButton("删除");
        deleteButton.setPreferredSize(new Dimension(100, 30));
        updateButton = new JButton("修改");
        updateButton.setPreferredSize(new Dimension(100, 30));
        searchButton = new JButton("查询");
        searchButton.setPreferredSize(new Dimension(100, 30));

        exitButton = new JButton("退出");
        refreshButton = new JButton("刷新");


        // 添加按钮点击事件监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GradeAdd();
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GradeDelete();
            }
        });
        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GradeUpdate();
            }
        });
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GradeSelect();
            }
        });
        exitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                tableModel.setRowCount(0);
                tableModel = GetDatabase();
                GradeTable.setModel(tableModel);
                scrollPane.setViewportView(GradeTable);
            }
        });

        // 创建学生信息表格模型
        tableModel = GetDatabase();
        GradeTable = new JTable(tableModel);

        // 创建滚动面板，并将表格添加到滚动面板中
        scrollPane = new JScrollPane(GradeTable);

        // 添加组件到面板
        //添加标题组件
        panel.add(jPanel, BorderLayout.NORTH);
        //添加功能按钮组件
        Panel rpanel = new Panel(new GridLayout(14, 2));
        rpanel.add(addButton);
        rpanel.add(Box.createVerticalStrut(10));
        rpanel.add(deleteButton);
        rpanel.add(Box.createVerticalStrut(10));
        rpanel.add(updateButton);
        rpanel.add(Box.createVerticalStrut(20));
        rpanel.add(searchButton);
        rpanel.add(Box.createVerticalStrut(10));
        rpanel.add(refreshButton);

        panel.add(rpanel, BorderLayout.EAST);
        //添加数据表组件
        panel.add(scrollPane, BorderLayout.CENTER);
        //添加退出按钮组件
        Panel exitpanel = new Panel();
        exitpanel.add(exitButton);
        panel.add(exitpanel, BorderLayout.SOUTH);

        // 设置面板居中显示
        panel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.setAlignmentY(Component.CENTER_ALIGNMENT);

        // 添加面板到窗口中心
        add(panel, BorderLayout.CENTER);

        // 设置窗口大小和可见性
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    //获取数据库信息并初始化表格内数据
    public DefaultTableModel GetDatabase() {
        DefaultTableModel tableModel = new DefaultTableModel();
        tableModel.addColumn("id");
        tableModel.addColumn("sno");
        tableModel.addColumn("cno");
        tableModel.addColumn("grade");

        StuGradeMapper stuGradeMapper = MyBatisUtils.getSqlSession();
        List<Grade> grades = stuGradeMapper.selectAll();
        for (Grade score : grades) {
            int id = score.getId();
            String sno = score.getSno();
            String cno = score.getCno();
            double grade = score.getGrade();
            // 将数据添加到表格模型
            tableModel.addRow(new Object[]{id, sno, cno, grade});
        }
        return tableModel;
    }
    //添加学生信息，id，姓名，sno，cno，grade等数据
    public void GradeAdd()  {
        int id = Integer.parseInt(JOptionPane.showInputDialog(this, "输入id"));
        String sno = JOptionPane.showInputDialog(this, "输入sno");
        String cno = JOptionPane.showInputDialog(this, "输入cno");
        double grade= Double.parseDouble(JOptionPane.showInputDialog(this,"输入学科成绩"));
        Grade grade1=new Grade(id,sno,cno,grade);

        //数据库连接
        StuGradeMapper stuGradeMapper = MyBatisUtils.getSqlSession();
        stuGradeMapper.addGrade(grade1);

        tableModel.addRow(new Object[]{id,sno,cno,grade});
    }
    public void GradeDelete(){
        int selectedRow = GradeTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的行");
            return;
        }
        // 确认是否要删除
        int option = JOptionPane.showConfirmDialog(this, "确定要删除所选行吗?", "确认删除", JOptionPane.YES_NO_OPTION);
        if (option == JOptionPane.YES_OPTION) {
            // 执行删除操作，例如从数据库中删除记录或更新集合等
            int gradeId = (int) tableModel.getValueAt(selectedRow, 0);//id为数据库索引，主键，选择删除id信息即可。

            System.out.println("gradeID" + gradeId);

            //数据库连接
            StuGradeMapper stuGradeMapper = MyBatisUtils.getSqlSession();
            stuGradeMapper.deleteGrade(gradeId);


            // 从表格模型中删除选中行
            tableModel.removeRow(selectedRow);

            JOptionPane.showMessageDialog(this, "删除成功");
        }
    }
    public void GradeUpdate(){
        //获取选定单元格的行列信息
        int selectedRow = GradeTable.getSelectedRow();
        int selectedColumn = GradeTable.getSelectedColumn();

        // 判断是否选定单元格
        if (selectedRow == -1 || selectedColumn == -1) {
            // 用户没有选择任何单元格
            JOptionPane.showMessageDialog(this, "请先选择一个单元格");
            return;
        }

        // 获取选定单元格的数据
        Object newValue = JOptionPane.showInputDialog(this, "请输入新的值:");

        // 如果用户取消输入或输入为空字符串
        if (newValue == null || ((String) newValue).isEmpty()) {
            int option = JOptionPane.showConfirmDialog(this, "您输入的值为空，是否继续修改数据", "确认修改", JOptionPane.YES_NO_OPTION);
            if (option == JOptionPane.NO_OPTION) {
                return;
            }
        }

        // 获取对应的学生唯一标识id信息
        int gradeId = (int) GradeTable.getValueAt(selectedRow, 0);
        String selectedName = GradeTable.getColumnName(selectedColumn);

        //数据库连接
        StuGradeMapper stuGradeMapper = MyBatisUtils.getSqlSession();
        // 执行更新操作，将修改后的数据更新到数据库
        stuGradeMapper.update(gradeId, selectedName, newValue);
        //GradeDAO.updateStuGrade(gradeId,selectedName,newValue);

        // 刷新表格显示，以更新修改后的数据
        tableModel.setValueAt(newValue, selectedRow, selectedColumn);

        // 提示数据更新成功
        JOptionPane.showMessageDialog(this, "数据更新成功");
    }
    public void GradeSelect(){
        //数据库连接
        StuGradeMapper stuGradeMapper = MyBatisUtils.getSqlSession();
        String[] options = {"按照学号查询", "按照课号查询", "按照成绩查询", "退出查询"};
        int choice = JOptionPane.showOptionDialog(null, "请按照以下功能查询或退出:", "查询功能", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
        switch (choice) {
            case 0:
                // 输入学号内容，查询学号学生信息
                String sno = JOptionPane.showInputDialog(this, "输入学生学号");
                List<Grade> grades1 = stuGradeMapper.selectByKeyword("sno",sno);
                CreateGrid("查询结果", grades1);
                System.out.println("按学号查询成功");
                break;
            case 1:
                // 输入课号内容，按照课号查询学生信息
                String cno = JOptionPane.showInputDialog(this, "输入课程课号");
                List<Grade> grades2 = stuGradeMapper.selectByKeyword("cno",cno);

                CreateGrid("查询结果", grades2);
                System.out.println("按课号查询成功");
                break;
            case 2:
                // 输入成绩内容，按照成绩查询学生信息
                double grade = Double.parseDouble(JOptionPane.showInputDialog(this, "输入成绩"));
                List<Grade> grades3 = stuGradeMapper.selectByKeyword("grade",grade);

                CreateGrid("查询结果", grades3);
                System.out.println("按成绩查询成功");
                break;
            case 3:
                System.out.println("退出查询");
                break;
        }
    }
    private static JFrame CreateGrid(String title, List<Grade> grades) {
        JFrame resultFrame = new JFrame(title);
        resultFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        // 创建表格
        JTable resultTable = new JTable();
        DefaultTableModel resultTableModel = new DefaultTableModel();

        // 添加表格列名
        resultTableModel.addColumn("ID");
        resultTableModel.addColumn("学生学号");
        resultTableModel.addColumn("课程号");
        resultTableModel.addColumn("成绩");

        // 添加查询结果到表格模型
        for (Grade grade : grades) {
            resultTableModel.addRow(new Object[]{grade.getId(), grade.getSno(), grade.getCno(), grade.getGrade()});
        }

        // 设置表格模型
        resultTable.setModel(resultTableModel);

        // 将表格添加到滚动面板
        JScrollPane scrollPane = new JScrollPane(resultTable);

        // 将滚动面板添加到窗口
        resultFrame.getContentPane().add(scrollPane);

        // 设置窗口大小和可见性
        resultFrame.setSize(400, 300);
        resultFrame.setVisible(true);
        return resultFrame;
    }
    public static void main(String[] args) {
        GradeForm a=new GradeForm();
        a.mainFrom();
    }
}
